class User
  include Mongoid::Document
  include Mongoid::Timestamps
  #include Mongoid::SoftDelete
  include ActiveModel::SecurePassword

  field :name, :type => String
  field :email, :type => String
  field :password_digest, :type => String
  field :avatar, :type => String
  field :admin, :type => Boolean,:default => false
  field :vip, :type => Boolean,:default => false
  field :verified, :type => Boolean, :default => false




  index({ :name => 1}, { :unique => true,:background=>true })
  index({ :email => 1}, { :unique => true,:background=>true })


  VAILD_NAME_REGEX = /\A[a-z0-9_.]{4,16}+\z/i
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email, :presence => true,
    :format => { :with => VALID_EMAIL_REGEX },
    :uniqueness => { :case_sensitive =>false }
  validates :name, :presence => true, :length => 4..16,
    :format => { :with => VAILD_NAME_REGEX },
    :uniqueness => { :case_sensitive =>false }
  validates :captcha,:presence => true

  has_secure_password

  validates :password, :presence => true, :length => 6..20, :confirmation => true
  validates :password_confirmation, :presence => true
  attr_accessor :captcha

  #用户认证
  def self.authentication(auth)
    user = User.find_by(:email => auth[:email]) || User.find_by(:name => auth[:email])
    return false if user.nil?
    if user && user.authenticate(auth[:password])
      return user
    end
    return false
  end


end
